////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2012 www.iflytek.com. All Rights Reserved.
//  This software for customer relationship management system, developed by Iflytek_ZY team.
//  Software code and design for the team, copy rights reserved.
////////////////////////////////////////////////////////////////////////////////

package com.iflytek.ci.common.service.impl;

import com.google.common.collect.Maps;
import com.iflytek.ci.common.service.MailService;
import com.iflytek.ci.cpms.domain.Project;
import com.iflytek.ci.main.dto.MailContent;
import com.iflytek.ci.qams.dao.PriopityDao;
import com.iflytek.ci.qams.domain.Comment;
import com.iflytek.ci.qams.domain.Issue;
import com.iflytek.ci.qams.domain.Priopity;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * MIME邮件服务类. Freemarker引擎生成的的html格式邮件, 可带有附件.
 * </p>
 * 
 * @author poplar.yfyang
 * @version 1.0 2012-11-10 11:24 AM
 * @since JDK 1.5
 */
@Service("mimeMailService")
public class MimeMailService implements MailService {
	/** 字符集 */
	private static final String DEFAULT_ENCODING = "utf-8";
	/** 日志 */
	private static Logger logger = LoggerFactory.getLogger(MimeMailService.class);
	/** 发送邮件 */
	@Qualifier("mailSender")
	@Autowired
	private JavaMailSender mailSender;
	/** 注入Freemarker 模板 */
	private Template template;
	/** 注入Freemarker 模板 */
	private Template template2;
	/** Spring 异步执行发送邮件 */
	@Autowired
	private TaskExecutor taskExecutor;
	
	@Autowired
	private PriopityDao priopityDao;

	/** 发送MIME格式的用户修改通知邮件. */
	@Override
	public void sendNotificationMail(final MailContent mailContent,
			final String to) {

		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				try {
					final MimeMessage msg = mailSender.createMimeMessage();
					final MimeMessageHelper helper = new MimeMessageHelper(msg,
							true, DEFAULT_ENCODING);

					final Issue issue = mailContent.getIssue();
					helper.setTo(to);
					helper.setFrom("gczx_support@iflytek.com");
					final Project project = mailContent.getProject();
					helper.setSubject(String.format("[%s]%s (issue:#%s)",
							project.getCode(), issue.getSummary(),
							issue.getPkey()));

					String content = generateContent(issue, project,
							mailContent.getComment());
					helper.setText(content, true);

					mailSender.send(msg);
					logger.info("HTML版邮件已发送至" + to);
				} catch (MessagingException e) {
					logger.error("构造邮件失败", e);
				} catch (Exception e) {
					logger.error("发送邮件失败", e);
				}
			}
		});

	}
    @Override
    public  void sendNotificationMailSimple(final String from,final String to,final String content,final String subject){

        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final MimeMessage msg = mailSender.createMimeMessage();
                    final MimeMessageHelper helper = new MimeMessageHelper(msg,
                            true, DEFAULT_ENCODING);
                    helper.setFrom(from);
                    helper.setTo(to);
                    helper.setSubject(subject);
                    helper.setText(content, true);
                    mailSender.send(msg);
                    logger.info("HTML版邮件已发送至" + to);
                } catch (MessagingException e) {
                    logger.error("构造邮件失败", e);
                } catch (Exception e) {
                    logger.error("发送邮件失败", e);
                }
            }
        });
    }
	/**
	 * 使用Freemarker生成html格式内容.
	 * 
	 * @param issue
	 *            问题详细
	 * @param project
	 *            项目信息
	 * @param comment
	 *            回复内容
	 * @return 生成的内容格式
	 * @throws javax.mail.MessagingException
	 *             生成异常
	 */
	private String generateContent(Issue issue, Project project, Comment comment)
			throws MessagingException {

		try {

			final Map<String, Object> context = Maps.newConcurrentMap();
			context.put("issue", issue);
			context.put("project", project);
			if (comment != null) {
				context.put("comment", comment);
				return FreeMarkerTemplateUtils.processTemplateIntoString(
						template, context);
			} else {
              Priopity priopity=priopityDao.get_priopity(issue.getPriopity());
              context.put("priopity", priopity);
			}
			return FreeMarkerTemplateUtils.processTemplateIntoString(template2,
					context);
		} catch (IOException e) {
			logger.error("生成邮件内容失败, FreeMarker模板不存在", e);
			throw new MessagingException("FreeMarker模板不存在", e);
		} catch (TemplateException e) {
			logger.error("生成邮件内容失败, FreeMarker处理失败", e);
			throw new MessagingException("FreeMarker处理失败", e);
		}
	}


	/**
	 * 注入Freemarker引擎配置,构造Freemarker 邮件内容模板.
	 * 
	 * @param freemarkerConfiguration
	 *            freemarker
	 * @throws java.io.IOException
	 *             IO异常
	 */
	@Autowired
	public void setFreemarkerConfiguration(@Qualifier("freemarkerConfiguration") Configuration freemarkerConfiguration)
			throws IOException {
		// 根据freemarkerConfiguration的templateLoaderPath载入文件.
		template = freemarkerConfiguration.getTemplate("issue_mail.ftl",
				DEFAULT_ENCODING);
		template2 = freemarkerConfiguration.getTemplate(
				"issue_mail_to_assignee.ftl", DEFAULT_ENCODING);
	}
}
